<template>
  <div class="interview-container">
    <!-- 顶部导航栏 -->
    <header class="interview-header">
      <div class="header-content">
        <h1>AI模拟面试</h1>
        <p class="header-subtitle">智能评估您的面试表现，提升求职竞争力</p>
      </div>
    </header>

    <!-- 主要内容区域 -->
    <main class="interview-main">
      <!-- 开始面试按钮 -->
      <div v-if="!sessionStarted && !report" class="start-section">
        <div class="start-card">
          <h2>准备开始模拟面试</h2>
          <p class="start-description">
            点击下方按钮开始AI模拟面试，系统会根据您的自我介绍进行针对性提问。
          </p>
          <button @click="startInterview" class="start-button">
            开始模拟面试 <i class="arrow-icon">→</i>
          </button>
        </div>
      </div>

      <!-- 面试对话框 -->
      <div v-if="sessionStarted && !report" class="interview-section">
        <div class="interview-card">
          <div class="chat-container" ref="chatContainer">
            <div v-for="(message, index) in messages" :key="index" class="message" :class="message.type">
              <div class="message-content">
                <div class="message-header">
                  <span class="sender-avatar" :class="message.type">
                    {{ message.type === 'bot' ? 'AI' : '你' }}
                  </span>
                  <span class="message-time">{{ formatTime(message.time) }}</span>
                </div>
                <div class="message-text">{{ message.content }}</div>
              </div>
            </div>
          </div>

          <div class="input-section">
            <div class="answer-container">
              <textarea
                  v-model="currentAnswer"
                  placeholder="请输入您的回答..."
                  class="answer-input"
                  rows="1"
                  @keyup.enter="submitAnswer"
                  @input="adjustTextareaHeight"
                  ref="answerInput"
              ></textarea>
            </div>
            <div class="action-buttons">
              <button
                  @click="submitAnswer"
                  class="submit-button"
                  :disabled="!currentAnswer.trim()"
                  :class="{disabled: !currentAnswer.trim()}"
              >
                提交答案
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 面试报告 -->
      <div v-if="report" class="report-section">
        <div class="report-card">
          <div class="report-header">
            <h2>面试分析报告</h2>
            <p class="report-date">生成时间: {{ formatReportTime() }}</p>
          </div>

          <div class="report-content">
            <div class="report-details">
              <div class="report-block">
                <h3 class="block-title">综合评估</h3>
                <div class="block-content">{{ report.summary }}</div>
              </div>
              <div class="report-block">
                <h3 class="block-title">技术能力分析</h3>
                <div class="block-content">{{ report.technical_analysis }}</div>
              </div>
              <div class="report-block">
                <h3 class="block-title">改进建议</h3>
                <div class="block-content">{{ report.suggestions }}</div>
              </div>
            </div>
          </div>

          <button @click="restartInterview" class="restart-button">
            重新开始面试
          </button>
        </div>
      </div>
    </main>
  </div>
</template>

<script>
import {ref, nextTick, onMounted} from 'vue'
import axios from 'axios'

export default {
  setup() {
    // 状态管理
    const sessionStarted = ref(false)
    const loading = ref(false)
    const report = ref(null)

    // 面试数据
    const messages = ref([])
    const currentAnswer = ref('')
    const answerInput = ref(null)

    // 方法
    const formatTime = (date) => {
      return date.toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'})
    }

    const formatReportTime = () => {
      const now = new Date()
      return `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')} ${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`
    }

    const addMessage = (type, content) => {
      messages.value.push({
        type,
        content,
        time: new Date()
      })
      nextTick(() => {
        const container = document.querySelector('.chat-container')
        if (container) {
          container.scrollTop = container.scrollHeight
        }
      })
    }

    const adjustTextareaHeight = () => {
      if (answerInput.value) {
        answerInput.value.style.height = 'auto'
        answerInput.value.style.height = `${Math.min(answerInput.value.scrollHeight, 150)}px`
      }
    }

    const startInterview = async () => {
      sessionStarted.value = true
      addMessage('bot', '您好！请简单介绍一下您的专业背景、工作经验和技能。')
    }

    const submitAnswer = async () => {
      if (!currentAnswer.value.trim()) return

      const answer = currentAnswer.value.trim()
      addMessage('user', answer)
      currentAnswer.value = ''
      adjustTextareaHeight()

      try {
        // 如果是第一次提交（自我介绍）
        if (messages.value.filter(m => m.type === 'user').length === 1) {
          const response = await axios.post('http://127.0.0.1:8000/home/interview/', {
            action: 'start',
            self_intro: answer
          }, {
            headers: {
              'X-CSRFToken': getCookie('csrftoken')
            }
          })

          const data = response.data
          addMessage('bot', data.greeting)
          addMessage('bot', data.first_question)
        } else {
          // 后续问题回答
          const response = await axios.post('http://127.0.0.1:8000/home/interview/', {
            action: 'submit_answer',
            answer: answer,
          }, {
            headers: {
              'X-CSRFToken': getCookie('csrftoken')
            }
          })

          const data = response.data
          if (data.status === 'completed') {
            // 处理报告数据
            const detailedReport = data.report.detailed_report
            const reportLines = detailedReport.split('\n')

            // 提取报告的不同部分
            let summary = ''
            let technicalAnalysis = ''
            let suggestions = ''
            let currentSection = ''

            for (const line of reportLines) {
              if (line.includes('综合能力评价') || line.includes('综合评估')) {
                currentSection = 'summary'
              } else if (line.includes('技术能力详细分析') || line.includes('技术能力分析')) {
                currentSection = 'technical'
              } else if (line.includes('改进建议') || line.includes('具体改进建议')) {
                currentSection = 'suggestions'
              }

              if (currentSection === 'summary') {
                summary += line + '\n'
              } else if (currentSection === 'technical') {
                technicalAnalysis += line + '\n'
              } else if (currentSection === 'suggestions') {
                suggestions += line + '\n'
              }
            }

            report.value = {
              summary: summary.trim(),
              technical_analysis: technicalAnalysis.trim(),
              suggestions: suggestions.trim()
            }
            sessionStarted.value = false
          } else {
            addMessage('bot', data.question)
          }
        }
      } catch (error) {
        console.error('提交失败:', error)
        alert(`操作失败: ${error.response?.data?.error || error.message}`)
      }
    }

    const restartInterview = () => {
      sessionStarted.value = false
      report.value = null
      messages.value = []
      currentAnswer.value = ''
    }

    const getCookie = (name) => {
      let cookieValue = null
      if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';')
        for (let i = 0; i < cookies.length; i++) {
          const cookie = cookies[i].trim()
          if (cookie.substring(0, name.length + 1) === (name + '=')) {
            cookieValue = decodeURIComponent(cookie.substring(name.length + 1))
            break
          }
        }
      }
      return cookieValue
    }

    onMounted(() => {
      axios.defaults.xsrfCookieName = 'csrftoken'
      axios.defaults.xsrfHeaderName = 'X-CSRFToken'
    })

    return {
      sessionStarted,
      loading,
      report,
      messages,
      currentAnswer,
      answerInput,
      formatTime,
      formatReportTime,
      addMessage,
      adjustTextareaHeight,
      startInterview,
      submitAnswer,
      restartInterview
    }
  }
}
</script>

<style scoped>
/* 基础样式 */
.interview-container {
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  color: #333;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 头部样式 */
.interview-header {
  background: linear-gradient(135deg, #1E63B3 0%, #0D47A1 100%);
  color: white;
  padding: 30px 0;
  border-radius: 0 0 12px 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.header-content {
  max-width: 1000px;
  margin: 0 auto;
  text-align: center;
}

.interview-header h1 {
  font-size: 2.5rem;
  font-weight: 600;
  margin: 0;
  letter-spacing: 1px;
}

.header-subtitle {
  font-size: 1.1rem;
  opacity: 0.9;
  margin-top: 10px;
}

/* 主要内容区域 */
.interview-main {
  margin: 30px 0;
  flex: 1;
}

/* 开始面试页面 */
.start-section {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 60vh;
}

.start-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  padding: 40px;
  text-align: center;
  max-width: 600px;
  width: 100%;
}

.start-card h2 {
  font-size: 1.8rem;
  color: #1E63B3;
  margin-top: 0;
  margin-bottom: 20px;
}

.start-description {
  font-size: 1rem;
  line-height: 1.6;
  color: #555;
  margin-bottom: 30px;
}

.start-button {
  background: linear-gradient(135deg, #1E63B3 0%, #0D47A1 100%);
  color: white;
  border: none;
  padding: 14px 24px;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.start-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(30, 99, 179, 0.3);
}

.arrow-icon {
  margin-left: 8px;
  transition: transform 0.3s;
}

.start-button:hover .arrow-icon {
  transform: translateX(3px);
}

/* 面试对话框 */
.interview-section {
  display: flex;
  justify-content: center;
}

.interview-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  width: 100%;
  max-width: 800px;
  display: flex;
  flex-direction: column;
  height: 70vh;
}

.chat-container {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background: #f9fafb;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.message {
  display: flex;
  flex-direction: column;
}

.message.bot {
  align-items: flex-start;
}

.message.user {
  align-items: flex-end;
}

.message-content {
  max-width: 85%;
  width: fit-content;
}

.message-header {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.sender-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 500;
  margin-right: 10px;
  font-size: 0.9rem;
}

.sender-avatar.bot {
  background: #e3f2fd;
  color: #1E63B3;
}

.sender-avatar.user {
  background: #1E63B3;
  color: white;
}

.message-time {
  font-size: 0.8rem;
  color: #999;
}

.message-text {
  padding: 12px 16px;
  border-radius: 8px;
  line-height: 1.5;
  word-break: break-word;
  position: relative;
}

.message.bot .message-text {
  background: white;
  border: 1px solid #e0e6ed;
  border-radius: 0 8px 8px 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.message.user .message-text {
  background: #1E63B3;
  color: white;
  border-radius: 8px 0 8px 8px;
}

.input-section {
  padding: 15px 20px;
  border-top: 1px solid #e0e6ed;
  background: white;
}

.answer-container {
  margin-bottom: 15px;
  max-height: 150px;
  overflow-y: auto;
  border: 1px solid #e0e6ed;
  border-radius: 8px;
}

.answer-input {
  width: 100%;
  padding: 12px 16px;
  border: none;
  font-size: 1rem;
  resize: none;
  background: transparent;
  min-height: 60px;
  outline: none;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
}

.submit-button {
  background: #1E63B3;
  color: white;
  border: none;
  padding: 12px 20px;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.submit-button:hover:not(.disabled) {
  background: #0D47A1;
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(30, 99, 179, 0.3);
}

.submit-button.disabled {
  background: #e0e6ed;
  cursor: not-allowed;
}

/* 面试报告 */
.report-section {
  display: flex;
  justify-content: center;
}

.report-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  width: 100%;
  max-width: 800px;
  padding: 30px;
}

.report-header {
  text-align: center;
  margin-bottom: 30px;
}

.report-header h2 {
  font-size: 1.8rem;
  color: #1E63B3;
  margin: 0;
}

.report-date {
  color: #666;
  margin-top: 8px;
  font-size: 0.9rem;
}

.report-details {
  margin-bottom: 30px;
}

.report-block {
  margin-bottom: 25px;
}

.block-title {
  font-size: 1.2rem;
  color: #1E63B3;
  border-bottom: 2px solid #e0e6ed;
  padding-bottom: 8px;
  margin-bottom: 15px;
}

.block-content {
  line-height: 1.6;
  color: #444;
  white-space: pre-line;
}

.restart-button {
  width: 100%;
  padding: 14px;
  background: linear-gradient(135deg, #1E63B3 0%, #0D47A1 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.restart-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(30, 99, 179, 0.3);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .interview-card, .report-card {
    height: auto;
    max-height: 80vh;
  }

  .message-content {
    max-width: 90%;
  }

  .sender-avatar {
    width: 28px;
    height: 28px;
    font-size: 0.8rem;
  }

  .message-text {
    padding: 10px 14px;
    font-size: 0.95rem;
  }

  .answer-container {
    max-height: 120px;
  }

  .answer-input {
    min-height: 50px;
  }
}
</style>